#include <cstddef>
#include <cstdio>
#include <cstdlib>
#include <iostream>

typedef struct Node {
    int data;
    struct Node *next;
} Node;

Node *initList() {
    Node *list = (Node *)malloc(sizeof(Node));
    list->data = 0;
    list->next = nullptr;
    return list;
}
bool headInsert(Node *list, int val) {
    if (list == nullptr)
        return false;
    Node *node = (Node *)malloc(sizeof(Node));
    node->data = val;
    node->next = list->next;
    list->next = node;
    list->data++;
    return true;
}
bool tailInsert(Node *list, int val) {
    if (list == nullptr)
        return false;
    Node *node = (Node *)malloc(sizeof(Node));
    node->data = val;
    node->next = nullptr;
    Node *p = list->next;
    while (p->next) {  // 判断是否到达最后一个节点，注意判断next指针是否为空
        p = p->next;
    }
    p->next = node;
    list->data++;
    return true;
}
bool deleteElement(Node *list, int val) {
    if (list == nullptr)
        return false;
    int flag = 0;
    Node *pre = list;
    Node *current = list->next;
    while (current) {
        if (current->data == val) {
            pre->next = current->next;
            free(current);
            list->data--;
            return true;
        } else {
            pre = current;
            current = current->next;
        }
    }
    return false;
}

void printList(Node *list) {
    Node *current = list->next;
    while (current) {
        printf("%3d", current->data);
        printf(" ->");
        current = current->next;
    }
    printf(" NULL\n");
    printf("List has %d node.\n\n", list->data);
    return;
}
void clear(Node *list) {
    if (list == nullptr)
        return;
    Node *pre = list;
    Node *current = list->next;
    if (current == nullptr)
        return;
    while (current->next) {
        pre->next = current->next;
        free(current);
        current = pre->next;
    }
    free(current);
    current = nullptr;
    free(list);
    list = nullptr;
    return;
}
int main() {
    srand(time(0));
    Node *list = initList();
    for (int i = 0; i < 5; i++) {
        headInsert(list, i + 1);
    }
    for (int i = 5; i <= 9; i++) {
        tailInsert(list, 7);
    }
    printList(list);
    while(deleteElement(list, 7)) {};
    printList(list);
    clear(list);
    return 0;
}